/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.tozo.service;

import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceState;
import hu.tozo.facade.AwsFacade;
import hu.tozo.model.AmazonModel;
import hu.tozo.rest.AmazonInstance;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;

/**
 * EC2 szolgaltasait meghivni kepes osztaly.
 * @author tozo
 */
//@Singleton
//@LocalBean
public class EC2Service {
    static String separator = System.getProperty("file.separator");
    static String homeDir = System.getProperty("user.home");
    AwsFacade amazon;
    ClusterController cc;
    
    public EC2Service() throws Exception{
        amazon = new AwsFacade();
       // cc     = new ClusterController();
    }
 
    public void startInstance(String instanceId){
        amazon.startInstance(instanceId);
    }
    public void stopInstance(String instanceId){
        amazon.stopInstance(instanceId);
    }
    public void startFirstStopedNode() throws Exception{
        String instance = getFirstStopedInstance();
        amazon.startInstance(instance);
    }
    public void stopFirstRunningdNode() throws Exception{
        String instance = getFirstRunningInstance();
        amazon.stopInstance(instance);
    }
    public int getInstanceState(String instanceID){
        int state = -1;
        state = amazon.getInstanceState(instanceID);
        return state;
    }

    /**
     * Feladata: Adja vissza az leallitott peldanyt Mukodes: Listazza ki a
     * peldanyokat A property file alapjan nezze meg a statusait a node
     * instanssoknak Adja vissza az elso stoped state instansot. Ha nem talal
     * leallitott peldanyit akkor adjon vissza null-t
     */
    public String getFirstStopedInstance() throws Exception {
        return getFirstInstance(80);
    }
    public String getFirstRunningInstance() throws Exception {
        
        return getFirstInstance(16);
    }

    /**
     * Feladata: Adja vissza az elso futo peldanyt
     *
     *
     * Mukodes: Listazza ki a peldanyokat. A property file alapjan nezze meg a
     * statusat a node instansoknak Adja vissza az elso running state instanceot
     * Ha nem talal instansot akkor adjon vissza null-t
     *   +--------+---------------+
     *   |  Code  |     State     |
     *   +--------+---------------+
     *   |   0    |    pending    | 
     *   |  16    |    running    |
     *   |  32    | shutting-down | 
     *   |  48    |  terminated   |
     *   |  64    |   stopping    | 
     *   |  80    |   stopped     |
     *   +--------+---------------+
     */
   
    public String getFirstInstance(int state) throws Exception {
        AwsFacade af = new AwsFacade();
        Properties clusterNodes = new Properties();
        clusterNodes.load(loadAwsClusterNodesProperties());
        
        af.listInstances();
        List<Instance> i = af.getInstances();
        for (Instance instance : i) {
            InstanceState is = instance.getState();
            String instanceId = instance.getInstanceId();
            if(is.getCode() == state && isClusterNode(instanceId)){
                return instance.getInstanceId();
            }
        }
        return "";
    }
    public List getAllInstance() throws Exception {
        AwsFacade af = new AwsFacade();
        ArrayList<AmazonModel> amazon = new ArrayList();
        Properties clusterNodes = new Properties();
        clusterNodes.load(loadAwsClusterNodesProperties());
        long id = 1;
        
        af.listInstances();
        List<Instance> i = af.getInstances();
        for (Instance instance : i) {
            InstanceState is = instance.getState();
            String instanceId = instance.getInstanceId();
            if(isClusterNode(instanceId)){
                AmazonModel am = new AmazonModel();
                am.setId(id++);
                am.setName(is.getName());
                am.setPublicDNS(instance.getPublicDnsName());
                am.setState(is.getName());
                amazon.add(am);
            }
        }
        return amazon;
    }
    
    public List getAllClusterInstanceIP(int state) throws Exception {
        ArrayList instances = new ArrayList();                          //Itt tárolom a futó példányokat
        AwsFacade af = new AwsFacade();                                 //AWS homlokzat példányosítás
        Properties clusterNodes = new Properties();                     //Property példányosítás
        clusterNodes.load(loadAwsClusterNodesProperties());             //Klaszter nodeok beöltése
        
        af.listInstances();                                             //Példányok listázása
        List<Instance> i = af.getInstances();                           //Lekéri az összes példányt, de menti a listázás
        for (Instance instance : i) {                                   //Végigiterálok mindegyiken
            InstanceState is = instance.getState();                     //Lekérem az aktuális példányt
            String instanceId = instance.getInstanceId();
            if(is.getCode() == state && isClusterNode(instanceId)){
                instances.add(instance.getPublicDnsName()); 
            }
        }
        return instances;
    }    
    
    public InputStream loadAwsClusterNodesProperties() throws FileNotFoundException {
        File f = new File(homeDir + separator + "aws" + separator + "AwsClusterNodes.properties");
        InputStream is = new FileInputStream(f);
        return is;
    }
    /**
     * Feladata:A parameterben kapott azonositorol dontse el, hogy resze a 
     * klaszter nodeok halmazanak.
     * Azert fontos mert definialhatunk mas tipusu gepek is ami nem resze a 
     * klaszternek.
     * 
     * Mukodes: 
     */
    public boolean isClusterNode(String instanceId) throws IOException{
        Properties p = new Properties();
        p.load(loadAwsClusterNodesProperties());
        Enumeration e = p.elements();
        while(e.hasMoreElements()){
            String value = (String)e.nextElement();
            if(value.equals(instanceId)){
                return true;
            }
        }
        
        return false;
    }
    public String getConvertInstanceId2NodeName(String instanceId) throws FileNotFoundException, IOException{
        Properties p = new Properties();
        p.load(loadAwsClusterNodesProperties());
        Enumeration e = p.propertyNames();
        while(e.hasMoreElements()){
            String key = (String)e.nextElement();
            String value = p.getProperty(key);
            if(value.equals(instanceId)){
                return key;
            }
        }        
        return null;
    }

}
